/**
 * 
 */
package fundacion;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;


public class JDBCFacade {


	private boolean connected;

	private Connection connection;

	public JDBCFacade() {
		connected = false;
	}

	public boolean connect(String driver, String uri) {
		boolean res = false;
		if (!connected) {
			try {
				Class.forName(driver);
				connection = DriverManager.getConnection(uri);
				res = connected = true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return res;
	}

	public boolean disconnect() {
		boolean res = true;

		if (connected) {
			if (connection != null) {
				try {
					connection.close();
					connection = null;
					connected = false;
				} catch (SQLException e) {
					e.printStackTrace();
					res = false;
				}
				// llegamos aqu� se la conexi�n es nula y connected es cierto,
				// se corrige dicho estado incorrecto.
			} else {
				connected = false;
			}
		}

		return res;
	}

	protected void finalize() {
		this.disconnect();
	}

	public List executeQuery(String query) {
		List lista = null;
		try {
			Statement stat = connection.createStatement();
			ResultSet res = stat.executeQuery(query);
			lista = (List) new ResultSetIterator(res);
		} catch (SQLException e) {
			e.printStackTrace();
			lista = (List) new ResultSetIterator();
		}
		return lista;
	}

	protected class ResultSetIterator{
		protected ResultSet rs;
		protected int numColumns;
		protected List<String> nameColumns;
		protected boolean endOfResults;
		protected boolean nextCalled;
		
		public ResultSetIterator() {
			this.rs = null;
			numColumns = 0;
			endOfResults = false;
			nextCalled = false;
		}
		
		public ResultSetIterator(ResultSet rs) {
			super();
			this.rs = rs;
			if ( rs != null ) {
				try {
					ResultSetMetaData meta = rs.getMetaData();
					numColumns = meta.getColumnCount();
					nameColumns = new LinkedList<String>();
					for (int i = 1; i <= numColumns; i++) {
						nameColumns.add(meta.getColumnName(i));
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
}
}
